package org.sems.sems.service.impl;

import org.sems.sems.Mapper.DataXsjlkMapper;

import org.sems.sems.Mapper.JlpjkMapper;
import org.sems.sems.entity.DataXsjlk;
import org.sems.sems.entity.Jlpjk;
import org.sems.sems.service.XsjlkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class XsjlkServiceImpl implements XsjlkService {
    @Autowired
    private DataXsjlkMapper xsjlkMapper;
    @Autowired
    private JdbcTemplate jdbcTemplate;


    /**
     * 根据学生ID获取学生简历
     *
     * @param stuId 学生ID
     * @return Map<String, Object> 学生简历
     */
    @Override
    public Map<String, Object> getStuResumeByStuId(int stuId) {
        Map<String, Object> stuResume = new HashMap<>();
        try {
            stuResume.put("code", 200);
            stuResume.put("msg", "success");
            stuResume.put("data", xsjlkMapper.getXsjlkByStuId(stuId));
            stuResume.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            stuResume.put("code", 500);
            stuResume.put("msg", "server fail");
            stuResume.put("result", false);
            stuResume.put("data", e.getMessage());
        }
        return stuResume;
    }

    /**
     * 通过存储过程获取学生简历数据
     *
     * @param yhm  用户姓名
     * @param jldm 简历代码
     * @return Map<String, Object> 教师简历
     */
    @Override
    public Map<String, Object> getXsjlDataAuto(String yhm, int jldm,int yhsfdm) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            List<Map<String, Object>> resultList;
            resultList = jdbcTemplate.queryForList(
                    "{call usp_getXsjlkData(?,?,?)}", yhm, jldm,yhsfdm);
            resultMap.put("data", resultList);
            resultMap.put("code", 200);
            resultMap.put("msg", "success");
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", 500);
            resultMap.put("msg", "server error");
            resultMap.put("result", false);
            resultMap.put("data", e.getMessage());
        }
        return resultMap;
    }

    /**
     * 保存学生简历
     *
     * @param dataXsjlk 学生简历数据
     * @return Map<String, Object> 保存结果
     */
    @Override
    public Map<String, Object> addResume(DataXsjlk dataXsjlk) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            //  添加工作经历数据
            if (xsjlkMapper.insertDataXsjlk(dataXsjlk) > 0) {
                resultMap.put("code", 200);
                resultMap.put("msg", "success");
                resultMap.put("result", true);
                resultMap.put("data", dataXsjlk);
            } else {
                resultMap.put("code", 500);
                resultMap.put("msg", "database error");
                resultMap.put("result", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", 500);
            resultMap.put("msg", "server error");
            resultMap.put("result", false);
            resultMap.put("data", e.getMessage());
        }
        return resultMap;
    }

    // 读取配置文件上传路径
    @Value("${video.upload.dir}")
    private String uploadDir;

    // 读取配置文件浏览器路径
    @Value("${app.domain}")
    private String appDomain;

    @Value("${app.WenJianJiaName}")
    private String WenJianJiaName;

    /**
     * 简历图片上传
     *
     * @param file 图片文件
     * @return Map<String, Object> 上传结果
     */
    @Override
    public Map<String, Object> uploadXSJLKkImg(MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 创建存储目录
            Path uploadPath = Paths.get(uploadDir);
            System.out.println("上传目录：" + uploadPath.toString());

            // 生成唯一文件名（防止重名覆盖）
            String originalFilename = file.getOriginalFilename();// 获取原始文件名

            // 获取当前时间戳
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));// 从原始文件名中获取文件扩展名
            String uniqueFileName = String.valueOf(System.currentTimeMillis()) + "_" + fileExtension;// 加上文件扩展名 UUID.randomUUID()生成唯一的字符串
            System.out.println("唯一文件名：" + uniqueFileName);
            System.out.println("原始文件名：" + originalFilename);
            System.out.println("文件扩展名：" + fileExtension);
            System.out.println("文件大小：" + file.getSize());
            System.out.println("文件类型：" + file.getContentType());
            System.out.println("新文件名：" + uniqueFileName);
            System.out.println("最终上场地址：" + uploadPath.toString() + "/" + "XSJLK/" + uniqueFileName);

            String ZuiZhongUrl = uploadPath.toString() + "/" + "XSJLK/" + uniqueFileName;
            System.out.println("最终上场地址2组合：" + ZuiZhongUrl);

            if (!Files.exists(Path.of(uploadPath.toString() + "/" + "XSJLK/"))) {
                Files.createDirectories(Path.of(uploadPath.toString() + "/" + "XSJLK/"));
                System.out.println("目录" + uploadPath.toString() + "/" + "XSJLK/" + "不存在，已创建目录成功!");
            }

            // 保存文件到本地
            Path filePath = Paths.get(ZuiZhongUrl);
            System.out.println("上传文件路径：" + filePath);
            System.out.println("浏览器路径:" + appDomain + "XSJLK/" + uniqueFileName);
            Files.copy(file.getInputStream(), filePath);
            result.put("code", 200);
            result.put("result", true);
            result.put("message", "success");
            result.put("data", WenJianJiaName + "XSJLK/" + uniqueFileName);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("result", false);
            result.put("code", 500);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 更新学生简历
     *
     * @param dataXsjlk 学生简历数据
     * @return Map<String, Object> 更新结果
     */
    @Override
    public Map<String, Object> updateResume(DataXsjlk dataXsjlk) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            //  添加工作经历数据
            if (xsjlkMapper.updateDataXsjlk(dataXsjlk) > 0) {
                resultMap.put("code", 200);
                resultMap.put("msg", "success");
                resultMap.put("result", true);
                resultMap.put("data", dataXsjlk);
            } else {
                resultMap.put("code", 500);
                resultMap.put("msg", "database error");
                resultMap.put("result", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", 500);
            resultMap.put("msg", "server error");
            resultMap.put("result", false);
            resultMap.put("data", e.getMessage());
        }
        return resultMap;
    }




    @Value("${app.WenJianJiaName}")
    private String folderName;

    /**
     * 上传简历附件
     *
     * @param jldm 简历代码
     * @param file
     * @return Map<String, Object> 删除结果
     */
    @Override
    public Map<String, Object> uploadJlfj(int jldm, MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        try {
            Map<String, String> urls = new HashMap<>();
            DataXsjlk dataXsjlk = new DataXsjlk();
            if (file != null && !file.isEmpty()) {
                String attachmentPath = saveFile(file, "");
                urls.put("attachmentUrl", folderName + "XSJLFJ/" + attachmentPath);
                // 数据更新
                dataXsjlk.setJldm(jldm);
                dataXsjlk.setJlfj(urls.get("attachmentUrl"));
                xsjlkMapper.updateDataXsjlk(dataXsjlk);
            } else {
                urls.put("fjUrl", "no attachment");
            }

            result.put("code", 200);
            result.put("result", true);
            result.put("data", urls);
        } catch (Exception e) {
            result.put("result", false);
            result.put("code", 500);
            result.put("message", "文件上传失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 新增简历评价
     *
     * @param jlpjk
     * @return Map<String, Object> 删除结果
     */
    @Override
    public Map<String, Object> addJpgj(Jlpjk jlpjk) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (jlpjkMapper.insertJlpjk(jlpjk) > 0) {
                resultMap.put("code", 200);
                resultMap.put("msg", "success");
                resultMap.put("result", true);
                resultMap.put("data", jlpjk);
            } else {
                resultMap.put("code", 500);
                resultMap.put("msg", "database error");
                resultMap.put("result", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", 500);
            resultMap.put("msg", "server error");
            resultMap.put("result", false);
            resultMap.put("data", e.getMessage());
        }
        return resultMap;
    }

    @Autowired
    private JlpjkMapper jlpjkMapper;

    /**
     * 更新简历评价
     *
     * @param jlpjk
     * @return Map<String, Object> 删除结果
     */
    @Override
    public Map<String, Object> updateJpgj(Jlpjk jlpjk) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            //  添加工作经历数据
            if (jlpjkMapper.updateJlpjk(jlpjk) > 0) {
                resultMap.put("code", 200);
                resultMap.put("msg", "success");
                resultMap.put("result", true);
                resultMap.put("data", jlpjk);
            } else {
                resultMap.put("code", 500);
                resultMap.put("msg", "database error");
                resultMap.put("result", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", 500);
            resultMap.put("msg", "server error");
            resultMap.put("result", false);
            resultMap.put("data", e.getMessage());
        }
        return resultMap;
    }

    /**
     * 获取简历评价列表
     *
     * @return Map<String, Object> 删除结果
     */
    @Override
    public Map<String, Object> getJpgjList(String yhm,int jldm, int yhsfdm) {

        Map<String, Object> resultMap = new HashMap<>();
        try {
            List<Map<String, Object>> resultList;
            resultList = jdbcTemplate.queryForList(
                    "{call usp_getXsjlPjData(?,?,?)}", yhm, jldm,yhsfdm);
            resultMap.put("data", resultList);
            resultMap.put("code", 200);
            resultMap.put("msg", "success");
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", 500);
            resultMap.put("msg", "server error");
            resultMap.put("result", false);
            resultMap.put("data", e.getMessage());
        }
        return resultMap;


    }

    /**
     * 撤销简历提交
     *
     * @param jldm
     * @return Map<String, Object> 删除结果
     */
    @Override
    public Map<String, Object> csSubmit(int jldm) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if (jlpjkMapper.deleteJlpjkByJldm(jldm) > 0) {
                resultMap.put("code", 200);
                resultMap.put("msg", "success");
                resultMap.put("result", true);
                resultMap.put("data", jldm);
            } else {
                resultMap.put("code", 500);
                resultMap.put("msg", "database error");
                resultMap.put("result", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", 500);
            resultMap.put("msg", "server error");
            resultMap.put("result", false);
            resultMap.put("data", e.getMessage());
        }
        return resultMap;
    }

    private String saveFile(MultipartFile file, String fileType) throws IOException {
        // 构建存储路径：video.upload.dir + WenJianJiaName + 文件类型目录
        Path storagePath = Paths.get(uploadDir, "XSJLFJ/", fileType);
        if (!Files.exists(storagePath)) {
            Files.createDirectories(storagePath);
        }

        // 生成文件名：时间戳_原始文件名
        String originName = file.getOriginalFilename();
        String fileName = System.currentTimeMillis() + "_" + (originName != null ? originName : "file");

        // 保存文件
        Files.copy(file.getInputStream(), storagePath.resolve(fileName));
        return fileName;
    }
}
